<?
require_once("../config/dbconn.php");require_once("../config/powercls.php");

//奖金结算
$lstperiods=$periods-1;

$sqlp="select * from {$db_prefix}salary where periods='$periods'";
$rsp=$db->get_one($sqlp);
$beginday=$rsp['beginday'];$endday=$rsp['endday'];
$jsstate=$rsp['state'];$jsstate1=$rsp['state1'];$jsfhprice=$rsp['fhprice'];

/*
$jsunixtime=mktime(0,0,0,$jsmonth,1,$jsyear);
$maxday=date('t',$jsunixtime);
$curjsmonth=$jsyear.'-'.$jsmonth;
$beginday=$jsyear.'-'.$jsmonth.'-01';
$endday=$jsyear.'-'.$jsmonth.'-'.$maxday;
$jstmptime=$jsyear*12+$jsmonth;
*/

//新增的业绩

$filter0=" and datediff(from_unixtime(confirmtime),'{$endday}')<=0";
$filter1=" and datediff(curday,'{$beginday}')>=0 and datediff(curday,'{$endday}')<=0";
$filter2=" and datediff(from_unixtime(confirmtime),'{$beginday}')>=0 and datediff(from_unixtime(confirmtime),'{$endday}')<=0";
$filter3=" and datediff(from_unixtime(ranktime1),'{$beginday}')>=0 and datediff(from_unixtime(ranktime1),'{$endday}')<=0";

//发放了就不能结算
if ($jsstate==2){
	die("本期奖金已经发放了.不能再次结算<br>");
}
if ($jsstate1==1){
	die("本期奖金正在被其他管理员结算中。请勿重复结算<br>");
}
//删除会员的年费记录
//$sqljl="delete from {$db_prefix}yearf where periods='$periods'";
//$db->query($sqljl);

if ($jsstate==1){
	$condition="periods='$periods'";
	$db->delete("{$db_prefix}salary1",$condition);
}

//插入到满足结算条件的会员到salary1
$sqlgx="insert into {$db_prefix}salary1(periods,userid,username,nickname,rank) select '$periods',id,username,nickname,rank from {$db_prefix}users where state=1 and datediff(from_unixtime(confirmtime,'%Y-%m-%d'),'{$endday}')<=0";
$db->query($sqlgx);

//拿返利
$sql="select * from {$db_prefix}salary1 where periods='$periods'";
$result=$db->query($sql);
while($rs=$db->fetch_array($result)){
	//推荐的推荐人数
	$flprice=0;
	
	$sqltj="select count(id) as c from {$db_prefix}users where tjuser='".trim($rs['username'])."' and state=1 and iskong=0".$filter0;
	$rstj=$db->get_one($sqltj);
	$tjnum=intval($rstj['c']);
	if ($tjnum>7) $tjnum=7;
	$glornamre="glo_fanli_{$tjnum}";
	$flprice=$$glornamre;
	$glornamfd="glo_fanlimax_{$tjnum}";
	$flpricefd=$$glornamfd;
	
	$sqlhy="select * from {$db_prefix}users where username='".trim($rs['username'])."'";
	$rshy=$db->get_one($sqlhy);
	if ($rshy['flprice']>=$flpricefd){
		$flprice=0;
	}else{
		if (($rshy['flprice']+$flprice)>$flpricefd){
			$flprice=$flpricefd-$rshy['flprice'];
		}
	}
	
	$sqlj="update {$db_prefix}salary1 set flprice='$flprice' where username='".trim($rs['username'])."' and periods='$periods'";
	$db->query($sqlj);
	
}
$db->free_result($result);


//结算完成以后更新数据
$sqlgx="update {$db_prefix}salary set state=1,state1=0,jstime='$curtime' where periods='$periods'";
$db->query($sqlgx);

echo "本期奖金结算完毕<bR>";
echo "<a href='salary_rec.php?periods={$periods}' style='color:red'>进入本期奖金列表</a>";
exit();
?>